package com.qf.blog.service.impl;

import com.qf.blog.commons.constant.BlogConstants;
import com.qf.blog.commons.constant.RedisKeys;
import com.qf.blog.vo.LikeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class LikeService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private PostScoreService postScoreService;

    public void onClick(LikeVo likeVo) {

        // 1、使用set来保存点赞的数据
        SetOperations<String, String> setOperations = stringRedisTemplate.opsForSet();

        // 2.准备点赞的key
        String likeKey = null;
        if (likeVo.getEntityType() == 1) {
            likeKey = String.format(RedisKeys.USER_LIKE_KEY, BlogConstants.POST, likeVo.getEntityId());
        } else if (likeVo.getEntityType() == 2) {
            likeKey = String.format(RedisKeys.USER_LIKE_KEY, BlogConstants.COMMENT, likeVo.getEntityId());
        }

        // 准备用户点赞的数量的key
        String userLikeKey = String.format(RedisKeys.USER_LIKE_KEY, BlogConstants.USER, likeVo.getEntityId());

        // 3.先判断一下当前用户是否对实体点过赞了
        Boolean member = setOperations.isMember(likeKey, likeVo.getUserId().toString());
        if (member) {
            // 如果已经存在说明点过赞了，就要取消点赞
            setOperations.remove(likeKey, likeVo.getUserId().toString());
            stringRedisTemplate.opsForValue().decrement(userLikeKey); //  用户的点赞数量-1
        } else {
            // 实现点赞
            setOperations.add(likeKey, likeVo.getUserId().toString());
            stringRedisTemplate.opsForValue().increment(userLikeKey); // 用户的点赞数量+1
        }

        // 4.帖子点赞和评论点赞，
        if (likeVo.getEntityType() == 1) {
            // 给帖子点赞需要计算帖子的分数
            postScoreService.addPostIdToRedis(likeVo.getEntityId());
        }
    }

    // 返回点赞实体的数量
    public Long getLikeCount(Integer type, Integer id) {
        String key = null;
        if (type == 1) {
            key = String.format(RedisKeys.USER_LIKE_KEY, BlogConstants.POST, id);
        } else if (type == 2) {
            key = String.format(RedisKeys.USER_LIKE_KEY, BlogConstants.COMMENT, id);
        }
        return stringRedisTemplate.opsForSet().size(key); // 传递一个key返回长度
    }

}
